package com.ruoyi.core.service.impl;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.core.domain.ClientProduct;
import com.ruoyi.core.mapper.*;
import com.ruoyi.core.service.IClientProductService;
import com.ruoyi.common.utils.RedisCacheKeyHelper;
import com.ruoyi.core.vo.ClientProductCreateOperationVO;
import com.ruoyi.core.vo.ClientProductUpdateOperationVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

/**
 * client_productService业务层处理
 *
 * @author ruoyi
 * @date 2020-09-28
 */
@Service
public class ClientProductServiceImpl implements IClientProductService {
    @Autowired
    private ClientProductMapper clientProductMapper;

    @Autowired
    private RedisCache redisCache;

    /**
     * 查询client_product
     *
     * @param id client_productID
     * @return client_product
     */
    @Override
    public ClientProduct selectClientProductById(Long id) {
        return clientProductMapper.selectClientProductById(id);
    }

    /**
     * 查询client_product列表
     *
     * @param clientProduct client_product
     * @return client_product
     */

    @Override
    public List<ClientProduct> selectClientProductList(ClientProduct clientProduct) {
        return clientProductMapper.selectClientProductList(clientProduct);
    }

    @Override
    public List<Map<String, Object>> selectSimpleClientProductList(ClientProduct clientProduct) {
        List<Map<String, Object>> clientProducts = clientProductMapper.selectSimpleClientProductList(clientProduct);
        if (clientProducts == null || clientProducts.isEmpty()) {
            return clientProducts;
        }

        clientProducts.forEach(item -> {
            Collection<String> keys = redisCache.keys(RedisCacheKeyHelper.getProductOnlineUserKey((Long) item.get("id")) + "*");
            item.put("users", (long) keys.size());
        });
        return clientProducts;

    }

    /**
     * 新增client_product
     *
     * @param clientProductCreateVO client_product
     * @return 结果
     */
    @Override
    @Transactional
    public int add(ClientProductCreateOperationVO clientProductCreateVO) {
        ClientProduct product = clientProductMapper.selectByProductName(clientProductCreateVO.getName());

        if (product != null) {
            throw new CustomException("客户端产品[" + clientProductCreateVO.getName() + "]已存在");
        }

        String logoUrl;
        try {
            // LOGO上传文件路径
            String filePath = RuoYiConfig.getUploadPath();

            // 上传并返回新文件名称
            logoUrl = FileUploadUtils.upload(filePath, clientProductCreateVO.getLogo());
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("客户端产品logo 文件上传失败");
        }

        ClientProduct clientProduct = new ClientProduct();
        BeanUtils.copyProperties(clientProductCreateVO, clientProduct);
        clientProduct.setLogo(logoUrl);
        clientProduct.setCreateTime(new Date());

        return clientProductMapper.insertClientProduct(clientProduct);
    }

    /**
     * 修改client_product
     *
     * @param productUpdateOperationVO client_product
     * @return 结果
     */
    @Override
    @Transactional
    public int updateClientProduct(ClientProductUpdateOperationVO productUpdateOperationVO) {
        if (clientProductMapper.selectClientProductById(productUpdateOperationVO.getId()) == null) {
            String message = String.format("客户端产品 id:[%s] 不存在", productUpdateOperationVO.getId());
            throw new CustomException(message);
        }

        String logoUrl = "";
        try {
            // LOGO上传文件路径
            MultipartFile logo = productUpdateOperationVO.getLogo();
            if (logo != null) {
                String filePath = RuoYiConfig.getUploadPath();
                // 上传并返回新文件名称
                logoUrl = FileUploadUtils.upload(filePath, logo);
            }

        } catch (Exception e) {
            throw new CustomException("客户端产品logo 文件上传失败");
        }

        ClientProduct clientProduct = new ClientProduct();
        BeanUtils.copyProperties(productUpdateOperationVO, clientProduct);
        clientProduct.setLogo(StringUtils.hasText(logoUrl) ? logoUrl : null);

        clientProduct.setUpdateTime(DateUtils.getNowDate());
        return clientProductMapper.updateClientProduct(clientProduct);
    }

    /**
     * 批量删除client_product
     *
     * @param ids 需要删除的client_productID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteClientProductByIds(Long[] ids) {

        SpringUtils.getBean(ClientProductBatchActivationCodeSummaryRelationMapper.class).deleteByProductIdSet(ids);
        SpringUtils.getBean(ClientUserProductRelationMapper.class).deleteByProductIdSet(ids);
        SpringUtils.getBean(ClientProductUserMapper.class).deleteByProductIdSet(ids);

        return clientProductMapper.deleteClientProductByIds(ids);
    }

    /**
     * 删除client_product信息
     *
     * @param id client_productID
     * @return 结果
     */
    @Override
    public int deleteClientProductById(Long id) {
        return clientProductMapper.deleteClientProductById(id);
    }

    @Override
    public List<Map<String, Object>> findByClientUserId(Long clientUserId) {
        List<Map<String, Object>> results = clientProductMapper.findByClientUserId(clientUserId);
        if (results != null && !results.isEmpty()) {
            results.forEach(item -> item.put("hasPermission", Boolean.valueOf((String) item.get("hasPermission"))));

        }
        return results;
    }
}
